import { defineEventHandler, getQuery, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { noteId } = getQuery(event);
    if (!noteId) {
      throw createError({ statusCode: 400, statusMessage: 'Note ID is required' });
    }

    const db = await getDbConnection();
    
    // 验证笔记是否属于当前用户
    const note = await db.get(
      'SELECT id FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );
    
    if (!note) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }
    
    // 获取版本历史
    const versions = await db.all(
      `SELECT id, version_number, name, change_summary, created_at,
              LENGTH(content) as content_length
       FROM note_versions 
       WHERE note_id = ? 
       ORDER BY version_number DESC`,
      [noteId]
    );

    return { success: true, versions };
  } catch (error) {
    console.error('Error fetching note versions:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to fetch note versions' });
  }
});
